package Work;
/*
 * 所谓的死锁就是线程一拥有锁1，线程二拥有锁2，
 * 双方在拥有自身锁的同时尝试获取对方的锁，
 * 最终两个线程就会进入无线等待的状态，这就是死锁。
 */
public class DieThread {
    private static final Object lock1 = new Object();
    private static final Object lock2 = new Object();
    public static void main(String[] args) {
        Thread t1 = new Thread(() -> {
            synchronized(lock1) {
                System.out.println("线程1拥有锁1");
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("线程1尝试拥有锁2");
                synchronized(lock2) {
                    System.out.println("线程1已经拥有锁2");
                }
            }
        });

        Thread t2 = new Thread(() -> {
            synchronized(lock2) {
                System.out.println("线程2拥有锁2");
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("线程2尝试拥有锁1");
                synchronized(lock1) {
                    System.out.println("线程2已经拥有锁1");
                }
            }
        });

        //启动线程
        t1.start();
        t2.start();
        //等待线程结束
        try {
            t1.join();
            t2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("线程结束");
    }
}
